package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyQianLaiShun;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeQianLaiShun;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 钱来顺api半流程采量-撞库返url
 * 文档链接：https://alidocs.dingtalk.com/i/nodes/vNG4YZ7JnPerjdYYc5orq1jlW2LD0oRE?utm_scene=team_space 密码：m2UGCI
 *
 * @author WJB
 */
@ApiPlan(productId = "7", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatQianLaiShunPhoneMd5ConvertV2 implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "kREvCfA3CaeCSDd4";
    private static final String ORG_ID = "202305161";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库实体类
        ApiPlatDataExchangeQianLaiShun data = new ApiPlatDataExchangeQianLaiShun();
        //  拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        //  手机号 MD5
        data.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        //  所在城市（如：成都市）
        data.setCity(apiDataExchangeParameter.getCity());
        //  城市编码
        data.setCityCode(apiDataExchangeParameter.getAreaCode());
        //  年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别1男2女0未知
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .end(1);
        data.setGender(sex);
        //  贷款时间2（6个月）3（12个月）4（24个月）5（36个月）
        Integer time = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "1", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 3)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 4)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 5)
                .when(apiDataExchangeParameter.getLoanTerm(), "6", 5)
                .end(2);
        data.setLoanTime(time);
        //  职业 1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）默认传1
        Integer career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 2)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 4)
                .when(apiDataExchangeParameter.getCareer(), "5", 2)
                .end(1);
        data.setProfession(career);
        //  芝麻分 1（600-650）2（650-700）3（700以上）4（无）5（600以下）
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 5)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 3)
                .end(4);
        data.setZhima(zhima);
        //  公积金1（6个月以下）2（6-12个月）3（12个月以上）4（无）
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 4)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(4);
        data.setProvidentFund(providentFund);
        //  社保1（6个月以下）2（6-12个月）3（12个月以上）4（无）
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 4)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(4);
        data.setSocialSecurity(socialSecurity);
        //  名下房产1（有房产）2（无房产）
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        data.setHouse(house);
        //  逾期记录1（信用良好）2（当前逾期中）
        Integer overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 1)
                .end(1);
        data.setOverdue(overdue);
        //  保单0（6个月以下）1（6-12个月）2（12个月以上）3（无）
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        data.setCommericalInsurance(baodanIs);
        //  名下车产1（有车产）2（无车产）
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(2);
        data.setVehicle(vehicle);
        //  贷款额度1（30000）2（50000）3（100000）4（200000）
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 1)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 2)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 3)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 4)
                .end(1);
        data.setLoanAmount(money);
        data.setAppKey(KEY);
        //  加密
        AES aes = AES.createEcb(KEY.getBytes());
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("data", aes.encryptToBase64Str(JsonUtils.toJson(data)));
            newMap.put("orgId", ORG_ID);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        //  分润前价格
        BigDecimal price = resData.getBigDecimal("price");
        if (price != null) {
            price = price.divide(BigDecimal.valueOf(0.8), 2, BigDecimal.ROUND_HALF_UP);
        }
        //  订单号
        String orderId = resData.getString("orderId");
        //  授权地址
        String url = resData.getString("redirectUrl");
        JSONArray resProtocolList = resData.getJSONArray("protocolList");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("protocolName"));
                    protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                    newList.add(protocol);
                }
            }
        });
        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setProtocolList(protocolList);
        result.setApplyId(orderId);
        result.setCallUrl(url);
        result.setDisplayName("钱来顺");
        result.setProductName("钱来顺");
        return result;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  进件实体类
        ApiPlatApplyQianLaiShun data = new ApiPlatApplyQianLaiShun();
        //  拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        data.setName(apiApplyParameter.getUserName());
        //  手机号
        data.setPhone(apiApplyParameter.getPhone());
        //  所在城市（如：成都市）
        data.setCity(apiApplyParameter.getCity());
        if (ValidParam.isEmpty(apiApplyParameter.getIp())) {
            data.setIp(apiApplyParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }
        //  城市编码
        data.setCityCode(apiApplyParameter.getAreaCode());
        //  年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别1男2女0未知
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 2)
                .end(1);
        data.setGender(sex);
        //  贷款时间2（6个月）3（12个月）4（24个月）5（36个月）
        Integer time = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "1", 2)
                .when(apiApplyParameter.getLoanTerm(), "2", 2)
                .when(apiApplyParameter.getLoanTerm(), "3", 3)
                .when(apiApplyParameter.getLoanTerm(), "4", 4)
                .when(apiApplyParameter.getLoanTerm(), "5", 5)
                .when(apiApplyParameter.getLoanTerm(), "6", 5)
                .end(2);
        data.setLoanTime(time);
        //  职业 1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）默认传1
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 2)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 4)
                .when(apiApplyParameter.getCareer(), "5", 2)
                .end(1);
        data.setProfession(career);
        //  芝麻分 1（600-650）2（650-700）3（700以上）4（无）5（600以下）
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 5)
                .when(apiApplyParameter.getSesameCredit(), "2", 1)
                .when(apiApplyParameter.getSesameCredit(), "3", 2)
                .when(apiApplyParameter.getSesameCredit(), "4", 3)
                .end(4);
        data.setZhima(zhima);
        //  公积金1（6个月以下）2（6-12个月）3（12个月以上）4（无）
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 4)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(4);
        data.setProvidentFund(providentFund);
        //  社保1（6个月以下）2（6-12个月）3（12个月以上）4（无）
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 4)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(4);
        data.setSocialSecurity(socialSecurity);
        //  名下房产1（有房产）2（无房产）
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        data.setHouse(house);
        //  逾期记录1（信用良好）2（当前逾期中）
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 1)
                .end(1);
        data.setOverdue(overdue);
        //  保单0（6个月以下）1（6-12个月）2（12个月以上）3（无）
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 3)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        data.setCommericalInsurance(baodanIs);
        //  名下车产1（有车产）2（无车产）
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 2)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 1)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(2);
        data.setVehicle(vehicle);
        //  贷款额度1（30000）2（50000）3（100000）4（200000）
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 1)
                .when(apiApplyParameter.getLoanAmount(), "2", 2)
                .when(apiApplyParameter.getLoanAmount(), "3", 3)
                .when(apiApplyParameter.getLoanAmount(), "4", 4)
                .end(1);
        data.setLoanAmount(money);
        data.setAppKey(KEY);
        data.setOrderId(apiApplyParameter.dataExchangeApplyId());
        data.setAgreeProtocol(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        //  加密
        AES aes = AES.createEcb(KEY.getBytes());
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("data", aes.encryptToBase64Str(JsonUtils.toJson(data)));
            newMap.put("orgId", ORG_ID);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String orgId = jsonObject.getString("orderId");
        String phoneMd5 = jsonObject.getString("phoneMd5");

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setApplyId(orgId);
        applyNotice.setPhoneMd5(phoneMd5);
        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {

        boolean b = apiBizStatus.hasBizSuc();

        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", 0);
                newHashMap.put("msg", "操作成功");
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", 500);
            newHashMap.put("msg", "操作失败");
        });
    }
}
